package cn.itcast.travel.web.servlet;

import cn.itcast.travel.domain.ResultInfo;
import cn.itcast.travel.domain.User;
import cn.itcast.travel.domain.vo.IndentVO;
import cn.itcast.travel.service.IndentService;
import cn.itcast.travel.service.UserService;
import cn.itcast.travel.service.impl.IndentServiceImpl;
import cn.itcast.travel.service.impl.UserServiceImpl;
import cn.itcast.travel.util.*;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.beanutils.BeanUtils;
import redis.clients.jedis.Jedis;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

@WebServlet("/user/*")
public class UserServlet extends BaseServlet {
    private   UserService userService=new UserServiceImpl();
    private  Jedis jedis = JedisUtil.getJedis();
    private IndentService is = new IndentServiceImpl();
    private ObjectMapper om = new ObjectMapper();

    /**
     * 用户注册
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void regist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String check = request.getParameter("check");
        String registerYzm = jedis.get(request.getSession().getAttribute("registTelephone")+"registerYzm");
        ResultInfo resultInfo=new ResultInfo();
        if (registerYzm==null || !registerYzm.equalsIgnoreCase(check)){
            resultInfo.setFlag(false);
            resultInfo.setErrorMsg("验证码错误");
            writeValue(resultInfo,response);
            return;
        }
        Map<String, String[]> parameterMap = request.getParameterMap();
        User user=new User();
        try {
            BeanUtils.populate(user,parameterMap);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        //UserService userService=new UserServiceImpl();
        boolean flag=userService.regist(user);
        ResultInfo info=new ResultInfo();
        if (flag){
            info.setFlag(true);
        }else {
            info.setFlag(false);
            info.setErrorMsg("注册失败");
        }
       writeValue(info,response);

    }

    /**
     * 用户登录
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ResultInfo resultInfo=new ResultInfo();
//        String check = request.getParameter("check");
//        String registerYzm = jedis.get(request.getSession().getAttribute("loginTelephone")+"loginYzm");
//
//        if (registerYzm==null||!registerYzm.equalsIgnoreCase(check)){
//            resultInfo.setFlag(false);
//            resultInfo.setErrorMsg("验证码错误");
//            writeValue(resultInfo,response);
//            return;
//        }
        Map<String, String[]> map = request.getParameterMap();
        User user=new User();
        try {
            BeanUtils.populate(user,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        //UserService userService=new UserServiceImpl();
        User  login=userService.login(user);
        if (login==null){
            resultInfo.setFlag(false);
            resultInfo.setErrorMsg("用户名或密码错误");
        }else {
            String id = request.getSession().getId();
            JedisUtil.addRedisObject(id,login);
            resultInfo.setFlag(true);
        }

        writeValue(resultInfo,response);
    }
    public void find(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Object login = JedisUtil.getRedisObject(request.getSession().getId());
        writeValue(login,response);
    }
    public void exit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //request.getSession().invalidate();
        JedisUtil.removeRedisObject(request.getSession().getId());
        response.sendRedirect(request.getContextPath()+"/login.html");
    }

    /**
     * 登录发送验证码
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void checkWord(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String yzm = CheckCodeServlet.getCheckCode();
        String username = request.getParameter("username");
        User userByUserName = userService.findUserByUserName(username);
        String telephone = userByUserName.getTelephone();
        String s = jedis.get(telephone);
        if (s==null){
            MessageUtil.sendMessage1(telephone,yzm);
            jedis.set(telephone+"loginYzm",yzm);
            //把查询到的手机号保存到session
            request.getSession().setAttribute("loginTelephone",telephone);
            jedis.expire(telephone+"loginYzm",60);
            jedis.set(telephone,"1");
            jedis.expire(telephone,3600);
            return;
        }
        int i = Integer.parseInt(s);
        if (i<=10){
            MessageUtil.sendMessage1(telephone,yzm);
            jedis.set(telephone+"loginYzm",yzm);
            //把查询到的手机号保存到session
            request.getSession().setAttribute("loginTelephone",telephone);
            jedis.expire(telephone+"loginYzm",60);
            jedis.set(telephone,(i+1)+"");
        }else {
            ResultInfo resultInfo=new ResultInfo();
            resultInfo.setErrorMsg("超过最大获取次数，每个小时只能发十条");
            writeValue(resultInfo,response);
        }
    }

    /**
     * 注册发送验证码
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void checkWord1(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String yzm = CheckCodeServlet.getCheckCode();
        String telephone = request.getParameter("telephone");
        String s = jedis.get(telephone);

        if (s==null){
            MessageUtil.sendMessage(telephone,yzm);
            jedis.set(telephone+"registerYzm",yzm);
            //把查询到的手机号保存到session
            request.getSession().setAttribute("registTelephone",telephone);
            jedis.expire(telephone+"registerYzm",60);
            jedis.set(telephone,"1");
            jedis.expire(telephone,3600);
            return;
        }
        int i = Integer.parseInt(s);
        if (i<=10){
            MessageUtil.sendMessage(telephone,yzm);
            jedis.set(telephone+"registerYzm",yzm);
            jedis.expire(telephone+"registerYzm",60);
            jedis.set(telephone,(i+1)+"");
        }else {
            ResultInfo resultInfo=new ResultInfo();
            resultInfo.setErrorMsg("超过最大获取次数，每个小时只能发十条");
            writeValue(resultInfo,response);

        }

    }

    /**
     * 人脸登录
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void faceLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String img = request.getParameter("img");
        String s = img.split(",")[1];
        String[] strings = FaceSearch.faceSearch(s);
        ResultInfo resultInfo=new ResultInfo();
        if (strings[0].equals("1")){
           resultInfo.setFlag(true);
            String string = strings[1];
            JSONObject jsonObject = JSONObject.parseObject(string);
            User user = JSONObject.toJavaObject(jsonObject, User.class);
            JedisUtil.addRedisObject(request.getSession().getId(),user);
        }else {
            resultInfo.setFlag(false);
            resultInfo.setErrorMsg("人脸识别失败");
        }
        writeValue(resultInfo,response);
    }
    public void faceRegister(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String img = request.getParameter("img");
        String s1 = img.split(",")[1];
        String s = FaceDetect.faceDetect(s1);
        String[] strings = FaceSearch.faceSearch(s1);
        int i = Integer.parseInt(strings[0]);
        if (s.equals("0")){
            ResultInfo resultInfo=new ResultInfo();
            resultInfo.setErrorMsg("未检测到人脸");
            writeValue(resultInfo,response);
            return;
        }
        if (i>80){
            ResultInfo resultInfo=new ResultInfo();
            resultInfo.setErrorMsg("人脸已注册");
            writeValue(resultInfo,response);
            return;
        }
        User login = (User) JedisUtil.getRedisObject(request.getSession().getId());
        ObjectMapper objectMapper=new ObjectMapper();
        String user = objectMapper.writeValueAsString(login);
        String add = FaceAdd.add(s1, user);
        ResultInfo resultInfo=new ResultInfo();
        if (add.equals("1")){
           resultInfo.setErrorMsg("注册成功");
        }else {
            resultInfo.setErrorMsg("注册失败");
        }
        writeValue(resultInfo,response);
    }

    /**
     * 快递单号查询
     * @param request
     * @param response
     * @throws IOException
     */
    public void select(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String kddh = request.getParameter("kddh");
        String getexpress = Express.Getexpress(kddh);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(getexpress);
    }

    /**
     * 订单查询
     */
    public void indent(HttpServletRequest request, HttpServletResponse response) throws IOException {

        //验证用户是否登录
        User redisObject = (User) JedisUtil.getRedisObject(request.getSession().getId());
        if(redisObject==null){
            return;
        }
        //调用service层获取订单的详细信息
        List<IndentVO> indent = is.getIndentVOByUid(redisObject.getUid()+"");
        String string = om.writeValueAsString(indent);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(string);
    }


}
